<?php
namespace addons\caipiao\service;

use addons\caipiao\model\Cplist;
use addons\caipiao\model\MpFriends;
use think\Db;
use think\facade\Cache;
use think\facade\Log;

class CplistService{
    public function __construct(){
        $this->cplistModel = new Cplist();
        $this->mpf = new MpFriends();
    }
    //判断MpFriends表存在用户
    private function isUserExs($openid){
        $id = $this->mpf->where(['openid'=>$openid])->value('id');
        return !empty($id);
    }

    public function lists($keyword,$page=1,$limit=20,$status = -1){
        $where=[];
        if($keyword!=''){
            $where['openid']=$keyword;
        }
        if($status!=-1){
            $where['status']=$status;
        }
        return Cplist::with('mpfriends')
            ->where($where)
            ->order('create_time','desc')
            ->page($page,$limit)
            ->select();
    }

    public function getCount($keyword,$status = -1){
        $where=[];
        if($keyword!=''){
            $where['openid']=$keyword;
        }
        if($status!=-1){
            $where['status']=$status;
        }
        return Cplist::with('mpfriends')
            ->where($where)
            ->count();
    }

    public function add($data){
        if($this->isUserExs($data['openid'])){
            Db::startTrans();
            try{
                $this->cplistModel->save([
                    'openid'=>$data['openid'],
                    'img_url'=>$data['img_url'],
                    'balance'=>$data['balance']
                ]);
                $this->mpf->save([
                    'mobile'=>$data['mobile'],
                    'relname'=>$data['relname']
                ],['openid'=>$data['openid']]);
                Db::commit();
                return true;
            }catch (\Exception $e){
                Db::rollback();
            }
        }
        return false;
    }

    public function edit($data){
        if($this->isUserExs($data['openid'])){
            Db::startTrans();
            try{
                $this->cplistModel->save([
                    'openid'=>$data['openid'],
                    'img_url'=>$data['img_url'],
                    'balance'=>$data['balance'],
                    'status'=>$data['status']
                ],['id'=>$data['id']]);
                $this->mpf->save([
                    'mobile'=>$data['mobile'],
                    'relname'=>$data['relname']
                ],['openid'=>$data['openid']]);
                Db::commit();
                return true;
            }catch (\Exception $exception){
                Log::notice($exception->getMessage());
                Db::rollback();
            }
        }
        return false;
    }
    //提现成功
    public function cashSuccess($id,$trade_no){
        return $this->cplistModel->save([
            'cash_type'=>1,
            'trade_no' =>$trade_no
        ],['id'=>$id]);
    }
    //扫码更新cplist表
    //1305兑奖失败，此票未中奖
    //1307兑奖失败，该票已经兑过奖
    //10000 兑奖成功
    /**
     * @param $cpId
     * @param $ret
     * @param $balance
     * @param false $autoCash 是否自动提现 默认手动提现
     * @return bool
     */
    public function scanUpdate(
        $cpId,
        $ret,
        $balance,
        $autoCash = false
    ){
        switch ($ret){
            case '1305':
                //1305兑奖失败，此票未中奖
                return $this->cplistModel->save([
                    'balance'=>0,
                    'status'=>2
                ],['id'=>$cpId]);
            case '1307':
                //1307兑奖失败，该票已经兑过奖
                return $this->cplistModel->save([
                    'balance'=>$balance,
                    'status'=>4
                ],['id'=>$cpId]);
            case '10000':
                //10000 兑奖成功
                if($autoCash){
                    //自动提现
                    $partner_trade_no = date('YmdHis').rand(100, 999).$cpId;
                    $qiyezf = new Qiyezf();
                    $openid = $this->cplistModel->where(['id'=>$cpId])->value('openid');
                    $result = $qiyezf->sendMoney($balance,$openid,$partner_trade_no,'彩票提现');
                    if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                        return $this->cplistModel->save([
                            'cash_type'=>1,
                            'trade_no' =>$partner_trade_no,
                            'balance'=>$balance,
                            'status'=>1
                        ],['id'=>$cpId]);
                    }else{
                        return false;
                    }
                }else{
                    //手工提现
                    return $this->cplistModel->save([
                        'balance'=>$balance,
                        'status'=>1
                    ],['id'=>$cpId]);
                }
            default:
                //默认是错误
                return $this->cplistModel->save([
                    'balance'=>0,
                    'status'=>3
                ],['id'=>$cpId]);
        }

    }
    //获取第一个待处理开奖任务
    public function getFirstTask($offset=0){
        //处理上一条图片不清晰的照片
        $cpid = Cache::pull('cpid');
        if(!empty($cpid)){
            Db::query("update rh_cplist set status=3 where id={$cpid} and scan_num>0");
        }
        $r = Db::query("select * from rh_cplist where status = 0 and scan_num = 0 order by id desc limit ?,1",[$offset]);
        if(count($r)==0){
            return false;
        }else{
            return $r[0];
        }
    }
    //扫码浏览次数记录+1
    public function recordScan($id){
        $scan_num = $this->getScanNum($id);
        if($scan_num == 0){
            $this->cplistModel
                ->where(['id'=>$id])
                ->setInc('scan_num');
        }
    }

    public function getScanNum($id){
        return $this->cplistModel
            ->where(['id'=>$id])
            ->value('scan_num');
    }
}
